﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Cashier.utils;
using Cashier_Service;
using Cashier_Model;
using Cashier_Utils;

namespace Cashier.rights
{
    public partial class RightsForm : Form
    {
        private MainForm mainform;
        private static RightsForm rightsform;
        private AdminService adminService;
        private RoleService roleService;
        private PurviewService purviewService;
        private RolePurviewService rolePurviewService;
        private Int64 adminRoleId = 0;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private RightsForm(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.adminService = new AdminService();
            this.roleService = new RoleService();
            this.purviewService = new PurviewService();
            this.rolePurviewService = new RolePurviewService();
            this.GenerateDataGridViewColumns();

            if (mainform.Admin.Username.ToLower().Equals("admin") || mainform.Admin.Isadmin)
                adminRoleId = mainform.Admin.Roleid;
            else
            {
                DataTable dt = adminService.GetAdminTable(0, 0, mainform.Admin.EnterpriseNo, mainform.Admin.StoreNo, 0);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        String isAdmin = row["is_admin"].ToString();
                        if (isAdmin.Equals("1") || isAdmin.ToLower().Equals("true"))
                        {
                            adminRoleId = (Int64)row["role_id"];
                            break;
                        }
                    }
                }
            }

            button_purview.Visible = false;
            //dataGridView1.ContextMenuStrip = this.contextMenuStrip_dgv;
            this.ControlsSetRights();
        }

        /// <summary>
        /// 返回RightsForm实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static RightsForm GetRightsForm(MainForm mainform)
        {
            if (rightsform == null)
                rightsform = new RightsForm(mainform);

            rightsform.LoadPurviewData();
            rightsform.InitialAdminListBox();
            rightsform.InitialRoleListBox();
            rightsform.SetSaveButtonRight(); 
            //rightsform.button_save.Enabled = true;
            return rightsform;
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_admin, button_role, button_save };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_admin, contextMenuStrip_role };
            RightsforControls.RightsforContextMenuStrip(mainform.Admin.RolePurviewtable, menuStrips);

            //设置权限按钮
            if (mainform.Admin.Isadmin)
            {
                toolItem_admin_delete.Enabled = false;
            }
        }

        /// <summary>
        /// 设置管理员保存按钮权限
        /// </summary>
        private void SetSaveButtonRight()
        {
            //设置权限按钮
            if (mainform.Admin.Username.ToLower().Equals("admin") || mainform.Admin.Isadmin)
            {
                Admin queryAdmin = adminService.GetAdmin(Convert.ToInt64(listBox_admin.SelectedValue));
                if (queryAdmin!=null && (queryAdmin.Isadmin || queryAdmin.Username.ToLower().Equals("admin")))
                {
                    button_save.Enabled = false;
                }
                else
                {
                    button_save.Enabled = false;
                    long roleid = Int64.Parse(listBox_role.SelectedValue.ToString());
                    if (adminRoleId == roleid)
                        button_save.Enabled = false;
                    else
                        button_save.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 生成数据列
        /// </summary>
        private void GenerateDataGridViewColumns()
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewCheckBoxColumn("选择", false, 10, ActKey.CENTER, ActKey.CENTER, true));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("name", "名称", true, 40, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("description", "描述", true, 50, ActKey.LEFT, ActKey.LEFT, true, false));
        }

        /// <summary>
        /// 初始化角色ListBox
        /// </summary>
        public void InitialRoleListBox()
        {
            try
            {
                DataTable dt_role = this.roleService.GetRoleTable(0, 0);
                List<DataItem> role_list = DataItem.GetDataItemList(dt_role, "name", "", "id");
                listBox_role.DataSource = role_list;
                listBox_role.DisplayMember = "displayMember";
                listBox_role.ValueMember = "valueMember";
                this.listBox_role.SelectedIndexChanged += new EventHandler(listBox_role_SelectedIndexChanged);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 初始化管理员ListBox
        /// </summary>
        public void InitialAdminListBox()
        {
            DataTable dt_admin = this.adminService.GetAdminTable(0, 0, mainform.Admin.EnterpriseNo, mainform.Admin.StoreNo, 0);
            List<DataItem> admin_list = DataItem.GetDataItemList(dt_admin, "username,name", " - ", "id");
            listBox_admin.DataSource = admin_list;
            listBox_admin.DisplayMember = "displayMember";
            listBox_admin.ValueMember = "valueMember";
            this.listBox_admin.SelectedIndexChanged += new EventHandler(listBox_admin_SelectedIndexChanged);
        }

        /// <summary>
        /// 设置管理员角色
        /// </summary>
        private void SetRoleForAdmin()
        {
            try
            {
                DataItem item = (DataItem)listBox_admin.SelectedItem;
                long adminid = Int64.Parse(item.ValueMember);
                Admin selectedAdmin = adminService.GetAdmin(adminid);
                if (selectedAdmin != null && selectedAdmin.Roleid > 0)
                {
                    listBox_role.Text = selectedAdmin.Rolename;
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 加载权限数据
        /// </summary>
        public void LoadPurviewData()
        {
            try
            {
                DataTable dt = this.purviewService.GetPurviewTable(0, 0);
                this.dataGridView1.DataSource = dt;
                dataGridView1.Columns[0].Visible = false;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 清空DataGridView选中行
        /// </summary>
        private void ClearDataGridViewSelectedRows()
        {
            foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
            {
                row.Selected = false;
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        private void DeletePurview()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除所选权限吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                    {
                        sb.Append(row.Cells["id"].Value.ToString()).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    int count = purviewService.DeletePurview(sb.ToString());
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！");
                        this.LoadPurviewData();
                    }
                    else
                        MessageBox.Show("删除失败！");
                }
            }
        }

        /// <summary>
        /// 设置角色权限
        /// </summary>
        private void SetRolePurview()
        {
            DataItem item = (DataItem)listBox_role.SelectedItem;
            long roleid = Int64.Parse(item.ValueMember);
            DataTable dt = this.rolePurviewService.GetRolePurviewTable(0, 0, roleid);

            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell checkBoxCell = (DataGridViewCheckBoxCell)row.Cells[1];
                long temp_purviewid = (long)row.Cells[0].Value;
                if (dt != null && dt.Rows.Count > 0)
                {
                    bool b = false;
                    foreach (DataRow dt_row in dt.Rows)
                    {
                        long purviewid = (long)dt_row["purview_id"];
                        if (purviewid == temp_purviewid)
                        {
                            b = true;
                            break;
                        }
                    }
                    checkBoxCell.Value = b;
                }
                else
                    checkBoxCell.Value = false;
            }
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// listBox_admin项选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_admin_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SetRoleForAdmin();
            Admin tempAdmin = this.adminService.GetAdmin(Int64.Parse(listBox_admin.SelectedValue.ToString()));
            if (tempAdmin.Isadmin)
                toolItem_admin_delete.Enabled = false;
            else
                toolItem_admin_delete.Enabled = true;
        }

        /// <summary>
        /// 添加权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_purview_Click(object sender, EventArgs e)
        {
            PurviewAddForm purviewAddForm = new PurviewAddForm(this, 0);
            purviewAddForm.ShowDialog();
        }

        /// <summary>
        /// 添加管理员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_admin_Click(object sender, EventArgs e)
        {
            AdminAddForm adminAddForm = new AdminAddForm(mainform, this, 0);
            adminAddForm.ShowDialog();
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_role_Click(object sender, EventArgs e)
        {
            RoleAddForm roleAddForm = new RoleAddForm(mainform, this, 0);
            roleAddForm.ShowDialog();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_save_Click(object sender, EventArgs e)
        {
            try
            {
                long adminid = Int64.Parse(listBox_admin.SelectedValue.ToString());
                long roleid = Int64.Parse(listBox_role.SelectedValue.ToString());

                rolePurviewService.DeleteRolePurview(roleid);
                RolePurview rolePurview = new RolePurview();
                rolePurview.Roleid = roleid;
                int insertCount = 0;
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    bool b = (bool)row.Cells[1].Value;
                    if (b)
                    {
                        long purviewid = (long)row.Cells[0].Value;
                        if (rolePurviewService.InsertRolePurview(roleid, purviewid) > 0)
                        {
                            insertCount += 1;
                        }
                    }
                }
                if (insertCount > 0)
                {
                    Admin tempAdmin = new Admin();
                    tempAdmin.Id = adminid;
                    tempAdmin.Roleid = roleid;
                    int flag = adminService.UpdateAdmin(tempAdmin);
                    if (flag > 0)
                    {
                        DialogResult result = MessageBox.Show("保存成功，下次登录软件生效，是否关闭窗口？", "提示", MessageBoxButtons.YesNo);
                        if (result == DialogResult.Yes)
                        {
                            this.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 取消事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 选择角色权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox_role_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SetRolePurview();
            this.SetSaveButtonRight();
        }

        /// <summary>
        /// 每当窗体第一次加载时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RightsForm_Shown(object sender, EventArgs e)
        {
            this.SetRoleForAdmin();
            this.SetRolePurview();
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RightsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            rightsform = null;
        }

        #endregion

        #region 权限右键菜单事件

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_purview_add_Click(object sender, EventArgs e)
        {
            PurviewAddForm purviewAddForm = new PurviewAddForm(this, 0);
            purviewAddForm.ShowDialog();
        }

        /// <summary>
        /// 编辑权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_purview_edit_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                long id = (long)this.dataGridView1.SelectedRows[0].Cells[0].Value;
                PurviewAddForm purviewAddForm = new PurviewAddForm(this, id);
                purviewAddForm.ShowDialog();
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_purview_delete_Click(object sender, EventArgs e)
        {
            this.DeletePurview();
        }

        #endregion

        #region 角色右键菜单事件

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_role_add_Click(object sender, EventArgs e)
        {
            RoleAddForm roleAddForm = new RoleAddForm(mainform, this, 0);
            roleAddForm.ShowDialog();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_role_edit_Click(object sender, EventArgs e)
        {
            long roleid = Int64.Parse(listBox_role.SelectedValue.ToString());
            RoleAddForm roleAddForm = new RoleAddForm(mainform, this, roleid);
            roleAddForm.ShowDialog();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_role_delete_Click(object sender, EventArgs e)
        {
            if (listBox_role.SelectedValue != null)
            {
                long roleid = Int64.Parse(listBox_role.SelectedValue.ToString());
                if (adminRoleId == roleid)
                {
                    MessageBox.Show("不能删除管理员的角色！");
                }
                else
                {
                    DialogResult result = MessageBox.Show("确定要删除选中的角色吗？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        int count = this.roleService.DeleteRole(roleid.ToString());
                        if (count > 0)
                        {
                            MessageBox.Show("删除成功！");
                            this.InitialRoleListBox();
                        }
                    }
                }
            }
        }

        #endregion

        #region 管理员右键菜单事件

        /// <summary>
        /// 新增管理员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_admin_add_Click(object sender, EventArgs e)
        {
            AdminAddForm adminAddForm = new AdminAddForm(mainform, this, 0);
            adminAddForm.ShowDialog();
        }

        /// <summary>
        /// 编辑管理员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_admin_edit_Click(object sender, EventArgs e)
        {
            long adminid = Int64.Parse(listBox_admin.SelectedValue.ToString());
            AdminAddForm adminAddForm = new AdminAddForm(mainform, this, adminid);
            adminAddForm.ShowDialog();
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolItem_admin_delete_Click(object sender, EventArgs e)
        {
            if (listBox_admin.SelectedValue != null)
            {
                String adminid = listBox_admin.SelectedValue.ToString();
                Admin admin = adminService.GetAdmin(Int64.Parse(adminid));
                if (admin != null && admin.Isadmin)
                {
                    MessageBox.Show("管理员不能删除？");
                    return;
                }

                DialogResult result = MessageBox.Show("确定要删除选中的管理员吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    int count = adminService.DeleteAdmin(adminid);
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！");
                        this.InitialAdminListBox();
                    }
                }
            }
        }

        #endregion
    }
}
